package org.chenliang.emulator.ui;

import org.cllib.data.Line;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;

public class Util {
	public static Rectangle getRectangleFromPoints(Point p1 , Point p2){
		int x = Math.min(p1.x, p2.x);
		int y = Math.min(p1.y, p2.y);
		int width = Math.abs(p1.x - p2.x);
		int height = Math.abs(p2.y - p1.y);
		return new Rectangle(x , y , width , height);
	}
	
	public static boolean intersect(Line l , Rectangle r){
		//Ax + By + C = 0
		//p1 (x1 , y1) p2 (y2 , y2)
		//(y2 - y1) * X + (x1 - x2) * Y + y1 * x2 - x1 * y2 = 0
		
		int x1 = l.x1;
		int y1 = l.y1;
		int x2 = l.x2;
		int y2 = l.y2;
		
		int a = y2 - y1;
		int b = x1 - x2;
		int c = y1 * x2 - x1 * y2;
		
		int left = r.x;
		int right = r.x + r.width;
		int top = r.y;
		int bottom = r.y + r.height;
		
		long lt = 1L * a * left + b * top + c;
		long rb = 1L * a * right + b * bottom + c;
		long lb = 1L * a * left + b * bottom + c;
		long rt = 1L * a * right + b * top + c;
		
		if((lt * rb <= 0) || (lb * rt <= 0)){
			if((x1 < left && x2 < left) || (x1 > right && x2 > right) || (y1 < top && y2 < top) || (y1 > bottom && y2 > bottom)){
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	}
}
